import React, { memo, useContext, useState } from 'react';

const numCtx = React.createContext<number>(0);
const updateCtx = React.createContext<React.Dispatch<React.SetStateAction<number>>>(() => { });

export default () => {
    const [num, updateNum] = useState(0);

    return (
        <numCtx.Provider value={num}>
            <updateCtx.Provider value={updateNum}>
                <Middle />
            </updateCtx.Provider>
        </numCtx.Provider>
    );
};

const Middle = memo(() => {
    console.log('middle rendered');
    return (
        <>
            <Button />
            <Show />
        </>
    );
});

const Button = () => {
    const updateNum = useContext(updateCtx);
    console.log('btn render');
    return <button onClick={() => updateNum(Math.random())}>随机数</button>;
};

const Show = () => {
    const num = useContext(numCtx);
    console.log('show render');
    return <p>num is {num}</p>;
};